package com.khotyn.heresy.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.SetAsEnvelopService;

/**
 * 设置封面控制类
 * 
 * @author 黄挺
 * 
 */
@Controller
@RequestMapping("/setAsEnvelop.html")
public class SetAsEnvelopController {
	@Autowired
	private SetAsEnvelopService setAsEnvelopService;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView onLoad(HttpServletRequest request, HttpSession session, @RequestParam(value = "pictureID") String pictureID,
			@RequestParam(value = "ownerID") String ownerIDStr) {
		Integer userID = (Integer) session.getAttribute("userID");
		Integer albumID = (Integer) session.getAttribute("albumID");
		HeresyErrorMessage message = null;

		try {
			validate(pictureID, ownerIDStr, userID, albumID);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		try {
			setAsEnvelopService.doService(pictureID, albumID, userID);
		} catch (Exception e) {
			// 不属于相册的图片
			e.printStackTrace();
			message = new HeresyErrorMessage("不属于相册的图片", "操作失败", "/Dragonfly/");
			return new ModelAndView("message", "message", message);
		}
		return new ModelAndView("redirect:/picture.html?pictureID=" + pictureID);
	}

	private void validate(String pictureID, String ownerIDStr, Integer userID, Integer albumID) throws IllegalUrlParamException {
		HeresyErrorMessage message = null;

		if (!NumberUtils.isDigits(ownerIDStr) || !NumberUtils.isDigits(pictureID)) {
			message = new HeresyErrorMessage("非法的参数", "操作失败", "/Dragonfly/");
		} else if (albumID == null) {
			message = new HeresyErrorMessage("您要把图片设为哪张相册的封面？", "操作失败", "picture.html?pictureID=" + pictureID);
		} else if (userID == null || userID != NumberUtils.toInt(ownerIDStr)) {
			message = new HeresyErrorMessage("您不是这样图片的所有者，无法将该图片设为封面", "操作失败", "/Dragonfly/");
		}

		if (message != null) {
			throw new IllegalUrlParamException(message);
		}
	}
}
